﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace MultiCastReceiver
{
    class Program
    {
        static void Main(string[] args)
        {
            // Socket Creation
            Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
            // Bind to port 50000
            listenSocket.Bind(new IPEndPoint(IPAddress.Any, 50000));
            // Ask to receive from a specific Multicast IP Address
            listenSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.1.1.42")));

            Console.WriteLine("This app will display the received strings and will quit when the sender will send the string \"Quit\".");
            byte []buffer = new byte[256];
            int recCount = 0;
            do
            {
                recCount = listenSocket.Receive(buffer);
                Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, recCount));
            } while (Encoding.UTF8.GetString(buffer, 0, recCount) != "Quit" );
        }
    }
}
